import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import 'record_data_widget.dart';
import 'record_data_manager.dart';

/// 录像数据组件使用示例
/// 展示如何在现有代码中使用组件化的录像数据管理
class RecordDataExample extends StatefulWidget {
  const RecordDataExample({super.key});

  @override
  State<RecordDataExample> createState() => _RecordDataExampleState();
}

class _RecordDataExampleState extends State<RecordDataExample> {
  String _deviceId = '34020000001310000001';
  String _channelId = '34020000001310000001';
  DateTime _selectedDate = DateTime.now();
  String _sourceType = 'cloud'; // 'cloud' 或 'local'

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('录像数据组件示例'),
        backgroundColor: Color(0xFF047FF7),
        foregroundColor: Colors.white,
      ),
      body: Column(
        children: [
          // 控制面板
          _buildControlPanel(),

          // 录像数据组件
          Expanded(
            child: RecordDataWidget(
              deviceId: _deviceId,
              channelId: _channelId,
              selectedDate: _selectedDate,
              sourceType: _sourceType,
              onDataLoaded: (segments) {
                print('✅ 录像数据加载完成，共 ${segments.length} 条记录');
                _showDataSummary(segments);
              },
              onError: (error) {
                print('❌ 录像数据加载失败: $error');
                _showErrorDialog(error);
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 构建控制面板
  Widget _buildControlPanel() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.05),
            offset: Offset(0, 2),
            blurRadius: 8,
          ),
        ],
      ),
      child: Column(
        children: [
          // 设备信息
          Row(
            children: [
              Expanded(
                child: Text(
                  '设备ID: $_deviceId',
                  style: TextStyle(fontSize: 24.sp),
                ),
              ),
              Expanded(
                child: Text(
                  '通道ID: $_channelId',
                  style: TextStyle(fontSize: 24.sp),
                ),
              ),
            ],
          ),
          SizedBox(height: 16.h),

          // 日期选择
          Row(
            children: [
              Text(
                '日期: ${_formatDateForDisplay(_selectedDate)}',
                style: TextStyle(fontSize: 24.sp),
              ),
              SizedBox(width: 16.w),
              ElevatedButton(onPressed: _selectDate, child: Text('选择日期')),
            ],
          ),
          SizedBox(height: 16.h),

          // 录像源切换
          Row(
            children: [
              Text('录像源:', style: TextStyle(fontSize: 24.sp)),
              SizedBox(width: 16.w),
              ChoiceChip(
                label: Text('云端'),
                selected: _sourceType == 'cloud',
                onSelected: (selected) {
                  if (selected) {
                    setState(() {
                      _sourceType = 'cloud';
                    });
                  }
                },
              ),
              SizedBox(width: 8.w),
              ChoiceChip(
                label: Text('本地'),
                selected: _sourceType == 'local',
                onSelected: (selected) {
                  if (selected) {
                    setState(() {
                      _sourceType = 'local';
                    });
                  }
                },
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 选择日期
  void _selectDate() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: DateTime(2020),
      lastDate: DateTime.now(),
    );

    if (picked != null && picked != _selectedDate) {
      setState(() {
        _selectedDate = picked;
      });
    }
  }

  /// 显示数据摘要
  void _showDataSummary(List<RecordSegment> segments) {
    final cloudCount = segments.where((s) => s.source == 'cloud').length;
    final localCount = segments.where((s) => s.source == 'local').length;
    final timeCount = segments.where((s) => s.type == 'time').length;
    final alarmCount = segments.where((s) => s.type == 'alarm').length;
    final manualCount = segments.where((s) => s.type == 'manual').length;

    Get.snackbar(
      '数据加载完成',
      '总记录: ${segments.length}\n'
          '云端: $cloudCount, 本地: $localCount\n'
          '定时: $timeCount, 报警: $alarmCount, 手动: $manualCount',
      duration: Duration(seconds: 3),
      backgroundColor: Color(0xFF4CAF50),
      colorText: Colors.white,
    );
  }

  /// 显示错误对话框
  void _showErrorDialog(String error) {
    Get.dialog(
      AlertDialog(
        title: Text('加载失败'),
        content: Text(error),
        actions: [TextButton(onPressed: () => Get.back(), child: Text('确定'))],
      ),
    );
  }

  /// 格式化日期显示
  String _formatDateForDisplay(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }
}

/// 高级使用示例：直接使用 RecordDataManager
class AdvancedRecordDataExample extends StatefulWidget {
  const AdvancedRecordDataExample({super.key});

  @override
  State<AdvancedRecordDataExample> createState() =>
      _AdvancedRecordDataExampleState();
}

class _AdvancedRecordDataExampleState extends State<AdvancedRecordDataExample> {
  final RecordDataManager _recordDataManager = RecordDataManager();
  final RxBool _isLoading = false.obs;
  final RxList<RecordSegment> _cloudSegments = <RecordSegment>[].obs;
  final RxList<RecordSegment> _localSegments = <RecordSegment>[].obs;

  @override
  void initState() {
    super.initState();
    _loadAllRecordData();
  }

  /// 加载所有录像数据（云端和本地）
  Future<void> _loadAllRecordData() async {
    _isLoading.value = true;

    try {
      // 并行加载云端和本地录像数据
      final results = await Future.wait([
        _recordDataManager.loadRecordData(
          deviceId: '34020000001310000001',
          channelId: '34020000001310000001',
          date: DateTime.now(),
          sourceType: 'cloud',
        ),
        _recordDataManager.loadRecordData(
          deviceId: '34020000001310000001',
          channelId: '34020000001310000001',
          date: DateTime.now(),
          sourceType: 'local',
        ),
      ]);

      _cloudSegments.value = results[0];
      _localSegments.value = results[1];

      print('✅ 所有录像数据加载完成');
      print('云端录像: ${_cloudSegments.length} 条');
      print('本地录像: ${_localSegments.length} 条');
    } catch (e) {
      print('❌ 加载录像数据失败: $e');
    } finally {
      _isLoading.value = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('高级录像数据示例'),
        backgroundColor: Color(0xFF047FF7),
        foregroundColor: Colors.white,
      ),
      body: Obx(() {
        if (_isLoading.value) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CircularProgressIndicator(),
                SizedBox(height: 16.h),
                Text('正在加载所有录像数据...'),
              ],
            ),
          );
        }

        return SingleChildScrollView(
          padding: EdgeInsets.all(16.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildDataSummary(),
              SizedBox(height: 24.h),
              _buildCloudRecords(),
              SizedBox(height: 24.h),
              _buildLocalRecords(),
            ],
          ),
        );
      }),
    );
  }

  /// 构建数据摘要
  Widget _buildDataSummary() {
    return Card(
      child: Padding(
        padding: EdgeInsets.all(16.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '数据摘要',
              style: TextStyle(fontSize: 32.sp, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 16.h),
            Row(
              children: [
                Expanded(
                  child: _buildSummaryItem(
                    '云端录像',
                    _cloudSegments.length,
                    Color(0xFF1976D2),
                  ),
                ),
                SizedBox(width: 16.w),
                Expanded(
                  child: _buildSummaryItem(
                    '本地录像',
                    _localSegments.length,
                    Color(0xFF7B1FA2),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建摘要项
  Widget _buildSummaryItem(String title, int count, Color color) {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: Column(
        children: [
          Text(title, style: TextStyle(fontSize: 24.sp, color: color)),
          SizedBox(height: 8.h),
          Text(
            '$count',
            style: TextStyle(
              fontSize: 36.sp,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建云端录像列表
  Widget _buildCloudRecords() {
    return Card(
      child: Padding(
        padding: EdgeInsets.all(16.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '云端录像 (${_cloudSegments.length})',
              style: TextStyle(fontSize: 28.sp, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 16.h),
            ..._cloudSegments.map((segment) => _buildRecordItem(segment)),
          ],
        ),
      ),
    );
  }

  /// 构建本地录像列表
  Widget _buildLocalRecords() {
    return Card(
      child: Padding(
        padding: EdgeInsets.all(16.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '本地录像 (${_localSegments.length})',
              style: TextStyle(fontSize: 28.sp, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 16.h),
            ..._localSegments.map((segment) => _buildRecordItem(segment)),
          ],
        ),
      ),
    );
  }

  /// 构建录像项
  Widget _buildRecordItem(RecordSegment segment) {
    return Container(
      margin: EdgeInsets.only(bottom: 12.h),
      padding: EdgeInsets.all(12.w),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: Row(
        children: [
          Icon(
            _getTypeIcon(segment.type),
            color: _getTypeColor(segment.type),
            size: 24.w,
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  segment.time,
                  style: TextStyle(
                    fontSize: 24.sp,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                Text(
                  '时长: ${segment.duration}',
                  style: TextStyle(fontSize: 20.sp, color: Colors.grey[600]),
                ),
              ],
            ),
          ),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
            decoration: BoxDecoration(
              color:
                  segment.source == 'cloud'
                      ? Color(0xFFE3F2FD)
                      : Color(0xFFF3E5F5),
              borderRadius: BorderRadius.circular(4.r),
            ),
            child: Text(
              segment.source == 'cloud' ? '云端' : '本地',
              style: TextStyle(
                fontSize: 20.sp,
                color:
                    segment.source == 'cloud'
                        ? Color(0xFF1976D2)
                        : Color(0xFF7B1FA2),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 获取录像类型颜色
  Color _getTypeColor(String type) {
    switch (type) {
      case 'time':
        return Color(0xFF4CAF50);
      case 'alarm':
        return Color(0xFFFF5722);
      case 'manual':
        return Color(0xFF2196F3);
      default:
        return Color(0xFF9E9E9E);
    }
  }

  /// 获取录像类型图标
  IconData _getTypeIcon(String type) {
    switch (type) {
      case 'time':
        return Icons.schedule;
      case 'alarm':
        return Icons.warning;
      case 'manual':
        return Icons.touch_app;
      default:
        return Icons.videocam;
    }
  }
}
